package com.df.excel_export.validator.vadator_impl.type_string;

import com.df.excel_export.common.ExcelTable;
import com.df.excel_export.validator.AbstractIFieldValidator;
import com.df.excel_export.validator.IFieldValidator;
import com.df.excel_export.validator.IValidatorFactory;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringRegValidator extends AbstractIFieldValidator implements IValidatorFactory {
    public String regex;
    @Override
    public boolean support(String filedType, String ruleStr) {
        if(!filedType.equals("string")){
            return false;
        }
        if(ruleStr.startsWith("regex(")&& ruleStr.endsWith(")")){
            return true;
        }
        return false;
    }

    @Override
    public IFieldValidator create(String filedType, String ruleStr) {
        StringRegValidator validator = new StringRegValidator();
        String substring = ruleStr.substring(6, ruleStr.length() - 1);
        validator.regex = substring;
        return validator;
    }

    @Override
    public Integer getPriority() {
        return 0;
    }

    @Override
    public boolean validate(ExcelTable checkTable, List<Object> rowData, Integer dataRowIndex, Integer fieldIndex, String fieldName, String fieldTypeStr, Object filedValue) {
        String value = (String) filedValue;
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        if(matcher.find()){
            return true;
        }
        return false;
    }
}
